'use client'

import { useState, useEffect } from 'react'
import { HotArticle } from 'app/api/hot-articles/route'
import { useSearchParams } from 'next/navigation'
import { Suspense } from 'react'

// 创建一个包装组件来处理Suspense
function AddHotArticlePageContent() {
  const searchParams = useSearchParams()
  const articleId = searchParams.get('id')
  
  const [isEditMode, setIsEditMode] = useState(false)
  const [searchKeyword, setSearchKeyword] = useState('')
  const [searchResults, setSearchResults] = useState<{ id: number; title: string }[]>([]);
  const [selectedArticle, setSelectedArticle] = useState<{ id: number; title: string } | null>(null)
  const [formData, setFormData] = useState<HotArticle>({
    post_id: 0,
    title: '',
    summary: '',
    publishTime: new Date().toISOString().split('T')[0],
    viewCount: 0,
    likeCount: 0,
    commentCount: 0,
    coverImage: '',
    tags: '',
    categoryName: ''
  })
  const [message, setMessage] = useState<{ type: 'success' | 'error' | ''; text: string }>({ type: '', text: '' })
  const [loading, setLoading] = useState(false)

  // 如果有articleId参数，则获取文章详情用于编辑
  useEffect(() => {
    if (articleId) {
      setIsEditMode(true)
      fetchArticleDetail(parseInt(articleId))
    }
  }, [articleId])

  // 获取文章详情
  const fetchArticleDetail = async (id: number) => {
    try {
      setLoading(true)
      const response = await fetch(`/api/hot-articles?id=${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      const result = await response.json()

      if (result.code === 200 && result.data) {
        const article = result.data
        setFormData({
          id: article.id,
          post_id: article.post_id,
          title: article.title,
          summary: article.summary || '',
          publishTime: article.publishTime ? new Date(article.publishTime).toISOString().split('T')[0] : new Date().toISOString().split('T')[0],
          viewCount: article.viewCount || 0,
          likeCount: article.likeCount || 0,
          commentCount: article.commentCount || 0,
          coverImage: article.coverImage || '',
          tags: article.tags || '',
          categoryName: article.categoryName || ''
        })
        setSelectedArticle({ id: article.post_id, title: article.title })
        setSearchKeyword(article.title)
      } else {
        setMessage({ type: 'error', text: result.message || '获取文章详情失败' })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '获取文章详情过程中发生错误' })
    } finally {
      setLoading(false)
    }
  }

  // 搜索文章
  const handleSearch = async () => {
    if (!searchKeyword.trim()) {
      setMessage({ type: 'error', text: '请输入文章名称' })
      return
    }

    setLoading(true)
    try {
      const response = await fetch(`/api/hot-articles?keyword=${encodeURIComponent(searchKeyword)}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      const result = await response.json()

      if (result.code === 200&&result.data&&result.data.length) {
        setSearchResults(result.data)
        setMessage({ type: '', text: '' })
      } else {
        setMessage({ type: 'error', text: result.message || '搜索失败' })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '搜索过程中发生错误' })
    } finally {
      setLoading(false)
    }
  }

  // 选择文章
  const handleSelectArticle = (article: { id: number; title: string }) => {
   
    setSelectedArticle(article)
    setFormData(prev => ({
      ...prev,
      post_id: article.id,
      title: article.title
    }))
    setSearchResults([])
    setSearchKeyword(article.title)
  }

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target
    
    // 对于数字类型的字段进行类型转换
    if (name === 'viewCount' || name === 'likeCount' || name === 'commentCount') {
      setFormData(prev => ({
        ...prev,
        [name]: value ? parseInt(value) : 0
      }))
    } else {
      setFormData(prev => ({
        ...prev,
        [name]: value
      }))
    }
  }

  // 提交表单
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    // 验证必填字段
    if (!formData.post_id || !formData.title) {
      setMessage({ type: 'error', text: '请搜索并选择文章' })
      return
    }

    setLoading(true)
    try {
      const method = isEditMode ? 'PUT' : 'POST'
      const url = '/api/hot-articles'
      
      const response = await fetch(url, {
        method: method,
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      })

      const result = await response.json()
      if (result.code === 200) {
        setMessage({ type: 'success', text: isEditMode ? '更新成功' : '添加成功' })
        if (!isEditMode) {
          // 重置表单（仅在添加模式下）
          resetForm()
        }
      } else {
        setMessage({ type: 'error', text: result.message || (isEditMode ? '更新失败' : '添加失败') })
      }
    } catch (error) {
      setMessage({ type: 'error', text: isEditMode ? '更新过程中发生错误' : '添加过程中发生错误' })
    } finally {
      setLoading(false)
    }
  }

  // 重置表单
  const resetForm = () => {
    setFormData({
      post_id: 0,
      title: '',
      summary: '',
      publishTime: new Date().toISOString().split('T')[0],
      viewCount: 0,
      likeCount: 0,
      commentCount: 0,
      coverImage: '',
      tags: '',
      categoryName: ''
    })
    setSelectedArticle(null)
    setSearchKeyword('')
    setSearchResults([])
  }

  // 删除文章
  const handleDelete = async () => {
    if (!isEditMode || !formData.id) {
      setMessage({ type: 'error', text: '无效操作' })
      return
    }

    if (!confirm('确定要删除这篇文章吗？')) {
      return
    }

    setLoading(true)
    try {
      const response = await fetch('/api/hot-articles', {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id: formData.id })
      })

      const result = await response.json()
      if (result.code === 200) {
        setMessage({ type: 'success', text: '删除成功' })
        // 重置表单
        resetForm()
        setIsEditMode(false)
      } else {
        setMessage({ type: 'error', text: result.message || '删除失败' })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '删除过程中发生错误' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="container mx-auto p-4 max-w-4xl">
      <h1 className="text-3xl font-bold mb-6 text-center">{isEditMode ? '编辑热门文章' : '添加热门文章'}</h1>
      
      {/* 消息提示 */}
      {message.text && (
        <div className={`mb-4 p-3 rounded ${message.type === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
          {message.text}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* 搜索文章部分 */}
        <div className="bg-gray-50 p-4 rounded-lg">
          <h2 className="text-xl font-semibold mb-4">搜索文章</h2>
          <div className="flex gap-2">
            <input
              type="text"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              placeholder="输入文章名称搜索"
              className="flex-1 px-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
              disabled={loading || (isEditMode && selectedArticle !== null)}
            />
            <button
              type="button"
              onClick={handleSearch}
              className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:bg-blue-300"
              disabled={loading || (isEditMode && selectedArticle !== null)}
            >
              {loading ? '搜索中...' : '搜索'}
            </button>
          </div>
          
          {/* 搜索结果 */}
          {searchResults.length > 0 && (
            <div className="mt-4 max-h-60 overflow-y-auto border border-gray-200 rounded">
              {searchResults.map((article) => (
                <div
                  key={article.id}
                  className="p-3 border-b border-gray-100 hover:bg-blue-50 cursor-pointer"
                  onClick={() => handleSelectArticle({ id: article.id, title: article.title })}
                  role="button"
                  tabIndex={0}
                >
                  {article.title}
                </div>
              ))}
            </div>
          )}
          
          {/* 已选择的文章 */}
          {selectedArticle && (
            <div className="mt-3 p-3 bg-green-50 rounded">
              <span className="text-green-700">已选择:</span> {selectedArticle.title}
            </div>
          )}
        </div>

        {/* 文章信息表单 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">文章标题 *</label>
            <input
              id="title"
              type="text"
              name="title"
              value={formData.title}
              onChange={handleInputChange}
              className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
              readOnly
            />
          </div>
          
          <div>
            <label htmlFor="viewCount" className="block text-sm font-medium text-gray-700 mb-1">浏览量</label>
            <input
              id="viewCount"
              type="number"
              name="viewCount"
              value={formData.viewCount}
              onChange={handleInputChange}
              className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
              min="0"
            />
          </div>
          
          <div>
            <label htmlFor="likeCount" className="block text-sm font-medium text-gray-700 mb-1">点赞数</label>
            <input
              id="likeCount"
              type="number"
              name="likeCount"
              value={formData.likeCount}
              onChange={handleInputChange}
              className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
              min="0"
            />
          </div>
          
          <div>
            <label htmlFor="commentCount" className="block text-sm font-medium text-gray-700 mb-1">评论数</label>
            <input
              id="commentCount"
              type="number"
              name="commentCount"
              value={formData.commentCount}
              onChange={handleInputChange}
              className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
              min="0"
            />
          </div>
          
          <div>
            <label htmlFor="categoryName" className="block text-sm font-medium text-gray-700 mb-1">分类名称</label>
            <input
              id="categoryName"
              type="text"
              name="categoryName"
              value={formData.categoryName}
              onChange={handleInputChange}
              placeholder="输入分类名称"
              className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          
          <div className="md:col-span-2">
            <label htmlFor="summary" className="block text-sm font-medium text-gray-700 mb-1">文章摘要</label>
            <textarea
              id="summary"
              name="summary"
              value={formData.summary}
              onChange={handleInputChange}
              placeholder="输入文章摘要"
              rows={3}
              className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          
          <div className="md:col-span-2">
            <label htmlFor="coverImage" className="block text-sm font-medium text-gray-700 mb-1">封面图片URL</label>
            <input
              id="coverImage"
              type="text"
              name="coverImage"
              value={formData.coverImage}
              onChange={handleInputChange}
              placeholder="输入封面图片URL"
              className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          
          <div className="md:col-span-2">
            <label htmlFor="tags" className="block text-sm font-medium text-gray-700 mb-1">标签 (逗号分隔)</label>
            <input
              id="tags"
              type="text"
              name="tags"
              value={formData.tags}
              onChange={handleInputChange}
              placeholder="输入标签，用逗号分隔"
              className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>

        <div className="flex justify-end gap-3">
          {isEditMode && (
            <button
              type="button"
              onClick={handleDelete}
              className="px-6 py-2 bg-red-600 text-white rounded hover:bg-red-700 disabled:bg-red-300"
              disabled={loading}
            >
              {loading ? '删除中...' : '删除'}
            </button>
          )}
          <button
            type="button"
            onClick={resetForm}
            className="px-6 py-2 border border-gray-300 rounded hover:bg-gray-100"
          >
            重置
          </button>
          <button
            type="submit"
            className="px-6 py-2 bg-green-600 text-white rounded hover:bg-green-700 disabled:bg-green-300"
            disabled={loading}
          >
            {loading ? (isEditMode ? '更新中...' : '提交中...') : (isEditMode ? '更新热门文章' : '添加热门文章')}
          </button>
        </div>
      </form>
    </div>
  )
}

// 主组件，包装在Suspense边界中
export default function AddHotArticlePage() {
  return (
    <Suspense fallback={<div>加载中...</div>}>
      <AddHotArticlePageContent />
    </Suspense>
  )
}